const express = require('express')
const axios = require('axios')
const cheerio = require('cheerio')
const { Manga, Chapter } = require('../models')
const { Op } = require('sequelize')
const router = express.Router()

// 支持的漫画源配置
const SOURCES = {
  mankezhan: {
    name: '漫客栈',
    baseUrl: 'https://www.mkzhan.com',
    searchUrl: '/search/?keyword=',
    mangaUrl: '/comic/',
    chapterUrl: '/chapter/',
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
  },
  dongman: {
    name: '咚漫',
    baseUrl: 'https://www.dongmanmanhua.cn',
    searchUrl: '/search?keyword=',
    mangaUrl: '/detail/',
    chapterUrl: '/viewer/',
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
  }
}

// 爬取漫画信息
router.post('/manga', async (req, res) => {
  try {
    const { url, source } = req.body

    if (!url || !source) {
      return res.status(400).json({ error: 'URL和source参数是必需的' })
    }

    if (!SOURCES[source]) {
      return res.status(400).json({ error: '不支持的漫画源' })
    }

    const mangaData = await crawlManga(url, source)
    
    // 保存到数据库
    const [manga, created] = await Manga.findOrCreate({
      where: {
        source,
        sourceId: mangaData.sourceId
      },
      defaults: mangaData
    })

    if (!created) {
      await manga.update(mangaData)
    }

    res.json({
      message: created ? '漫画信息已保存' : '漫画信息已更新',
      data: manga
    })
  } catch (error) {
    console.error('爬取漫画错误:', error)
    res.status(500).json({ error: '爬取失败' })
  }
})

// 爬取章节
router.post('/chapters', async (req, res) => {
  try {
    const { mangaId } = req.body

    const manga = await Manga.findByPk(mangaId)
    if (!manga) {
      return res.status(404).json({ error: '漫画不存在' })
    }

    const chapters = await crawlChapters(manga.sourceUrl, manga.source)
    
    // 保存章节
    const savedChapters = []
    for (const chapterData of chapters) {
      const [chapter, created] = await Chapter.findOrCreate({
        where: {
          mangaId,
          sourceId: chapterData.sourceId
        },
        defaults: {
          ...chapterData,
          mangaId
        }
      })

      if (!created) {
        await chapter.update(chapterData)
      }
      
      savedChapters.push(chapter)
    }

    // 更新漫画的章节数和最后更新时间
    await manga.update({
      totalChapters: savedChapters.length,
      lastUpdate: new Date()
    })

    res.json({
      message: `已更新 ${savedChapters.length} 个章节`,
      data: savedChapters
    })
  } catch (error) {
    console.error('爬取章节错误:', error)
    res.status(500).json({ error: '爬取失败' })
  }
})

// 检查更新
router.post('/check-updates', async (req, res) => {
  try {
    const { mangaId } = req.body

    const manga = await Manga.findByPk(mangaId, {
      include: [{
        model: Chapter,
        as: 'chapters',
        attributes: ['chapterNumber', 'sourceId']
      }]
    })

    if (!manga) {
      return res.status(404).json({ error: '漫画不存在' })
    }

    const latestChapters = await crawlChapters(manga.sourceUrl, manga.source)
    
    // 找出新章节
    const existingChapters = manga.chapters.map(c => c.sourceId)
    const newChapters = latestChapters.filter(
      chapter => !existingChapters.includes(chapter.sourceId)
    )

    if (newChapters.length === 0) {
      return res.json({ message: '暂无新章节', data: [] })
    }

    // 保存新章节
    const savedChapters = []
    for (const chapterData of newChapters) {
      const chapter = await Chapter.create({
        ...chapterData,
        mangaId
      })
      savedChapters.push(chapter)
    }

    // 更新漫画信息
    await manga.update({
      totalChapters: manga.totalChapters + savedChapters.length,
      lastUpdate: new Date()
    })

    res.json({
      message: `发现 ${savedChapters.length} 个新章节`,
      data: savedChapters
    })
  } catch (error) {
    console.error('检查更新错误:', error)
    res.status(500).json({ error: '检查更新失败' })
  }
})

// 爬取漫画信息的函数
async function crawlManga(url, source) {
  const config = SOURCES[source]
  
  try {
    const response = await axios.get(url, {
      headers: config.headers
    })
    
    const $ = cheerio.load(response.data)
    
    let mangaData = {
      source,
      sourceUrl: url,
      sourceId: extractSourceId(url, source),
      title: '',
      author: '',
      description: '',
      cover: '',
      categories: [],
      tags: [],
      status: 'ongoing'
    }

    // 根据漫画源解析数据
    switch (source) {
      case 'mankezhan':
        mangaData.title = $('.comic-title h1').text().trim()
        mangaData.author = $('.author-name').text().trim()
        mangaData.description = $('.comic-desc').text().trim()
        mangaData.cover = $('.comic-cover img').attr('src')
        mangaData.categories = $('.comic-tags a').map((i, el) => $(el).text().trim()).get()
        break
        
      case 'dongman':
        mangaData.title = $('.detail-title').text().trim()
        mangaData.author = $('.detail-author').text().trim()
        mangaData.description = $('.detail-desc').text().trim()
        mangaData.cover = $('.detail-cover img').attr('src')
        mangaData.categories = $('.detail-tags a').map((i, el) => $(el).text().trim()).get()
        break
        
      default:
        throw new Error('不支持的漫画源')
    }

    return mangaData
  } catch (error) {
    console.error('爬取漫画信息失败:', error)
    throw error
  }
}

// 爬取章节列表的函数
async function crawlChapters(mangaUrl, source) {
  const config = SOURCES[source]
  
  try {
    const response = await axios.get(mangaUrl, {
      headers: config.headers
    })
    
    const $ = cheerio.load(response.data)
    const chapters = []

    // 根据漫画源解析章节
    switch (source) {
      case 'mankezhan':
        $('.chapter-list li').each((i, el) => {
          const $el = $(el)
          const chapterUrl = $el.find('a').attr('href')
          chapters.push({
            title: $el.find('.chapter-title').text().trim(),
            chapterNumber: parseFloat($el.find('.chapter-number').text()),
            sourceUrl: config.baseUrl + chapterUrl,
            sourceId: extractSourceId(chapterUrl, source),
            publishedAt: new Date($el.find('.chapter-time').text())
          })
        })
        break
        
      case 'dongman':
        $('.episode-list li').each((i, el) => {
          const $el = $(el)
          const chapterUrl = $el.find('a').attr('href')
          chapters.push({
            title: $el.find('.episode-title').text().trim(),
            chapterNumber: parseFloat($el.find('.episode-number').text()),
            sourceUrl: config.baseUrl + chapterUrl,
            sourceId: extractSourceId(chapterUrl, source),
            publishedAt: new Date($el.find('.episode-time').text())
          })
        })
        break
        
      default:
        throw new Error('不支持的漫画源')
    }

    return chapters.sort((a, b) => a.chapterNumber - b.chapterNumber)
  } catch (error) {
    console.error('爬取章节列表失败:', error)
    throw error
  }
}

// 提取源ID的辅助函数
function extractSourceId(url, source) {
  const patterns = {
    mankezhan: /\/(\d+)\.html/,
    dongman: /\/(\d+)\//
  }
  
  const match = url.match(patterns[source])
  return match ? match[1] : null
}

// 获取支持的漫画源
router.get('/sources', (req, res) => {
  res.json({ 
    data: Object.entries(SOURCES).map(([key, config]) => ({
      key,
      name: config.name,
      baseUrl: config.baseUrl
    }))
  })
})

module.exports = router
